<template>
  <div class="app-container">
    <el-form :model="queryForm" ref="queryForm" inline v-show="showSearch">
      <el-form-item label="围栏名称" prop="fenceName">
        <el-input v-model="queryForm.fenceName" placeholder="请输入围栏名称" clearable @keyup.enter="getFenceRecordList"/>
      </el-form-item>
      <el-form-item label="工号" prop="userName">
        <el-input v-model="queryForm.userName" placeholder="请输入工号" clearable @keyup.enter="getFenceRecordList"/>
      </el-form-item>
      <el-form-item label="姓名" prop="nickName">
        <el-input v-model="queryForm.nickName" placeholder="请输入姓名" clearable @keyup.enter="getFenceRecordList"/>
      </el-form-item>
      <el-form-item label="方向" prop="direction">
        <el-select v-model="queryForm.direction" placeholder="规则方向" clearable>
          <el-option v-for="rule in fenceRuleMap" :value="rule.value" :label="rule.label"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="getFenceRecordList">搜索</el-button>
        <el-button icon="Refresh" @click="resetQueryForm">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="table-tools mb8">
      <div>
        <el-button type="danger"
                   icon="Delete"
                   plain
                   :disabled="fenceRecordTableMultiple"
                   @click="handleDeleteFenceRecordList"
                   v-hasPermi="['core:fence-record:remove']">删除</el-button>
      </div>
      <div>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getFenceRecordList"/>
      </div>
    </div>

    <el-table :data="recordList"
              ref="recordList"
              v-loading="recordLoading"
              @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection"/>
      <el-table-column align="center" type="index" label="序号" width="80"/>
      <el-table-column align="center" prop="user.userName" label="工号"/>
      <el-table-column align="center" prop="user.nickName" label="姓名"/>
      <el-table-column align="center" prop="fence.name" label="围栏名称"/>
      <el-table-column align="center" prop="direction" label="方向" :formatter="directionFormatter"/>
      <el-table-column align="center" label="位置">
        <template #default="{row}">
          <el-button type="primary"
                     text
                     bg
                     icon="MapLocation"
                     @click="openLocationDialog(row)">查看位置</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="createTime" label="时间"/>
      <el-table-column align="center" label="操作">
        <template #default="{row}">
          <el-button type="primary"
                     link
                     icon="Delete"
                     v-hasPermi="['core:fence-record:remove']"
                     @click="handleDeleteFenceRecord(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination :total="recordTotal"
                v-model:page="queryForm.pageNum"
                v-model:limit="queryForm.pageSize"
                @pagination="getFenceRecordList"/>

    <el-dialog title="电子围栏规则事件位置"
               width="40%"
               :close-on-press-escape="false"
               :close-on-click-modal="false"
               :before-close="beforeCloseLocationDialog"
               append-to-body
               destroy-on-close
               v-model="locationDialogVisible">
      <div class="map-container" ref="mapContainer"/>
    </el-dialog>
  </div>
</template>

<script>
import {getFenceRecordList, deleteFenceRecord} from "@/api/core/fenceRecord";
import {key, keyCode} from "@/constant/amap";
import {fenceRule, fenceRuleMap} from "@/constant/fenceRule";
import AMapLoader from "@amap/amap-jsapi-loader";
import {markRaw} from "vue";

export default {
  name: "index",
  data() {
    return {
      queryForm: {
        userName: '',
        nickName: '',
        fenceName: '',
        direction: '',
        pageNum: 1,
        pageSize: 10
      },
      showSearch: true,
      fenceRecordTableMultiple: true,
      recordList: [],
      recordTotal: 0,
      recordLoading: false,
      locationDialogVisible: false,
      map: null,
      fenceRule,
      fenceRuleMap
    }
  },
  created() {
    this.getFenceRecordList()

  },
  methods: {
    getFenceRecordList() {
      this.recordLoading = true
      getFenceRecordList(this.queryForm).then(res => {
        const {total, rows} = res
        this.recordList = rows
        this.recordTotal = total
      }).finally(() => {
        this.recordLoading = false
      })
    },
    resetQueryForm() {
      this.queryForm = {
        userName: '',
        nickName: '',
        fenceName: '',
        direction: '',
        pageNum: 1,
        pageSize: 10
      }
      this.getFenceRecordList()
    },
    handleSelectionChange(selection) {
      this.fenceRecordTableMultiple = !selection.length
    },
    async deleteFenceRecord(recordIds) {
      await deleteFenceRecord(recordIds)

      this.getFenceRecordList()
      this.$modal.msgSuccess('删除成功')
    },
    async handleDeleteFenceRecordList() {
      const rows = this.$refs.recordList.getSelectionRows()
      const recordIds = rows.map(item => item.id)

      await this.$modal.confirm('您确定要删除勾选的数据吗？')
      await this.deleteFenceRecord(recordIds)
    },
    async handleDeleteFenceRecord(row) {
      await this.$modal.confirm('您确定要删除此条数据吗？')

      const recordIds = [row.id]
      await this.deleteFenceRecord(recordIds)
    },
    async loadMapAndLocation(row) {
      if (!window.AMap) {
        window._AMapSecurityConfig = {
          securityJsCode: keyCode
        }
        try {
          await AMapLoader.load({
            key,
            version: '2.0',
            plugins: ['AMap.MouseTool', 'AMap.ContextMenu', 'AMap.PolyEditor', 'AMap.MapType', 'AMap.Scale', 'AMap.OverView',
              'AMap.ControlBar', 'Map3D', 'AMap.DistrictSearch', 'AMap.MarkerClusterer', 'AMap.ToolBar', 'AMap.Geolocation']
          })
        } catch (e) {
          this.$modal.msgError('地图加载失败')
        }
      }

      this.map = markRaw(new AMap.Map(this.$refs.mapContainer, {
        resizeEnable: true,
        rotateEnable: true,
        pitchEnable: true,
        showLabel: true,
        zoom: 16,
        zooms: [2, 30],
        rotation: 0,
        viewMode: '3D',
        skyColor: '#132237'
      }))
      this.map.addControl(new AMap.ToolBar())
      this.map.addControl(new AMap.ControlBar({
        position: 'LT'
      }))
      this.map.addControl(new AMap.Scale())
      this.map.addControl(new AMap.MapType())

      const path = row.fence.points.map(item => [item.longitude, item.latitude])
      const polygon = new AMap.Polygon({
        path,
        strokeColor: "red",
        strokeWeight: 3,
        strokeOpacity: 0.8,
        fillOpacity: 0.5,
        fillColor: 'white',
        extData: {
          fenceId: row.fence.id,
          fenceName: row.fence.name,
        }
      })
      this.map.add(polygon)
      this.map.setFitView([polygon])

      const marker = new AMap.Marker({
        position: [row.longitude, row.latitude],
        anchor: 'bottom-center'
      })
      this.map.add(marker)
    },
    openLocationDialog(row) {
      this.locationDialogVisible = true
      this.$nextTick(() => {
        this.loadMapAndLocation(row)
      })
    },
    beforeCloseLocationDialog(done) {
      if (this.map) {
        this.map.destroy()
        this.map = null
      }
      done()
    },
    directionFormatter(row) {
      return this.fenceRuleMap[row.direction].label
    },

  }

}
</script>

<style scoped lang="scss">
.map-container {
  height: 500px;
}
</style>
